package com.ktjiaoyu.server.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.ktjiaoyu.server.utils.Base64;
import com.ktjiaoyu.server.utils.RedisCache;
import com.ktjiaoyu.server.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @auth wzy
 * @date 2023/2/17 9:56
 * @description 验证码处理器
 */
@Api(tags = "验证码接口")
@RestController
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisCache redisCache;

    @ApiOperation(value = "获取验证码")
    @GetMapping(value = "/captcha")
    public ResponseResult captcha() {

        // 获取验证码文本内容
        String text = defaultKaptcha.createText();
        // 将验证码文本内容放入缓存中
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        redisCache.setCacheObject(RedisCache.CAPTCHA_CODE_KEY+uuid,text,5, TimeUnit.MINUTES);
        // 根据文本验证码内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return ResponseResult.error(e.getMessage());
        }

        String base64Img = Base64.encode(os.toByteArray());

        ResponseResult responseResult = ResponseResult.success();
        responseResult.put("img",base64Img);
        responseResult.put("uuid",uuid);

        return responseResult;
    }
}